﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using System.Data.Objects;
using Relocation.Com.Tools;
using Relocation.Com;
using System.Data.Objects.DataClasses;
using Relocation.Base;
using System.Drawing;
using System.Threading;
using Relocation.Base.UI;
using Relocation.Data;

namespace Relocation.UI
{
	public partial class RelocateesWindow : BaseForm
	{
		#region 变量

		private string person;  //保存修改前户主姓名
		private Relocatee Relocatee;

		/// <summary>
		/// Tab标签内的安置人员列表
		/// </summary>
		private PlacementList TabListPlacement;
		/// <summary>
		/// Tab标签内的安置房列表
		/// </summary>
		private Relocatees_HouseList TabListRelocateesHouse;

		public Relocatees_HouseList GetRelocateesHouseList()
		{
			if (TabListRelocateesHouse == null)
			{
				this.InitRelocatees_HouseList(this.Relocatee);
			}
			return TabListRelocateesHouse;
		}
		public PlacementList GetPlacementList()
		{
			if (TabListPlacement == null)
			{
				this.InitPlacementList(this.Relocatee);
			}
			return this.TabListPlacement;
		}

		#endregion

		#region 构造函数
		public RelocateesWindow()
			: base()
		{
			InitializeComponent();
			Initialize();
		}

		/// <summary>
		/// 新增
		/// </summary>
		/// <param name="session"></param>
		public RelocateesWindow(Session session)
			: base(session)
		{
			InitializeComponent();
			Initialize();
		}

		/// <summary>
		///  修改拆迁户信息
		/// </summary>		
		public RelocateesWindow(Session session, Relocatee relocatee)
			: this(session)
		{
			this.Relocatee = relocatee;
			this.SetValue(this.Relocatee);
		}

		#endregion

		/// <summary>
		/// 控件属性配置
		/// </summary>
		private void Initialize()
		{
			this.tabPages.Visible = false;
			this.Visible = false;
			InitCombobox();  //村别下拉框选择
			ValidatorInfo vInfo_Digit_Req = new ValidatorInfo(true, ValidatorInfo.ValidatorTypes.Digit);
			ValidatorInfo vInfo = new ValidatorInfo(true, ValidatorInfo.ValidatorTypes.Number);
			this.Field_Money1.Tag = new ControlTag(Relocatee.GetPropName(t => t.money1), vInfo_Digit_Req, null, null);
			this.Field_Money2.Tag = new ControlTag(Relocatee.GetPropName(t => t.money2), vInfo_Digit_Req, null, null);
			this.Field_Money3.Tag = new ControlTag(Relocatee.GetPropName(t => t.money3), vInfo_Digit_Req, null, null);
			this.Field_Payment.Tag = new ControlTag(Relocatee.GetPropName(t => t.payment), vInfo_Digit_Req, null, null);
			this.Field_Area.Tag = new ControlTag(Relocatee.GetPropName(t => t.area), null, null, null);
			this.Field_HouseType1.Tag = new ControlTag(Relocatee.GetPropName(t => t.housetype1), new ValidatorInfo(true, ValidatorInfo.ValidatorTypes.Number), null, null);
			this.Field_HouseType2.Tag = new ControlTag(Relocatee.GetPropName(t => t.housetype2), new ValidatorInfo(true, ValidatorInfo.ValidatorTypes.Number), null, null);
			this.Field_HouseType3.Tag = new ControlTag(Relocatee.GetPropName(t => t.housetype3), new ValidatorInfo(true, ValidatorInfo.ValidatorTypes.Number), null, null);
			this.Field_HouseType4.Tag = new ControlTag(Relocatee.GetPropName(t => t.housetype4), new ValidatorInfo(true, ValidatorInfo.ValidatorTypes.Number), null, null);
			this.Field_HouseType5.Tag = new ControlTag(Relocatee.GetPropName(t => t.housetype5), new ValidatorInfo(true, ValidatorInfo.ValidatorTypes.Number), null, null);
			this.Field_HouseType6.Tag = new ControlTag(Relocatee.GetPropName(t => t.housetype6), new ValidatorInfo(true, ValidatorInfo.ValidatorTypes.Number), null, null);
			this.Field_HouseType7.Tag = new ControlTag(Relocatee.GetPropName(t => t.housetype7), new ValidatorInfo(true, ValidatorInfo.ValidatorTypes.Number), null, null);
			this.Field_principal.Tag = new ControlTag(Relocatee.GetPropName(t => t.principal));
			this.Field_Persons.Tag = new ControlTag(Relocatee.GetPropName(t => t.persons), new ValidatorInfo(true, ValidatorInfo.ValidatorTypes.Number), null, null);
			this.Field_Village.Tag = new ControlTag(Relocatee.GetPropName(t => t.village), new ValidatorInfo(true));
			this.Field_Organization.Tag = new ControlTag(Relocatee.GetPropName(t => t.organization));
			this.Field_Head.Tag = new ControlTag(Relocatee.GetPropName(t => t.head), new ValidatorInfo(true));
			this.Field_AreaType.Tag = new ControlTag(Relocatee.GetPropName(t => t.areaType));
			this.Field_Remark.Tag = new ControlTag(Relocatee.GetPropName(t => t.remark));
			this.ButtonSave.Tag = new ControlTag(new RoleInfo(Session.KEY_ROLE_ADMIN, Session.KEY_ROLE_OPERATOR));
		}



		#region 加载、初始化
		/// <summary>
		/// form load 权限控制
		/// </summary>
		private void RelocateesWindow_Load(object sender, EventArgs e)
		{
			return;
		}

		/// <summary>
		/// combox村别及单位下拉框
		/// </summary>
		public void InitCombobox()
		{
			this.Field_Village.DataSource = this.Session.Project.Relocatees.CreateSourceQuery().Select(t => t.village).Distinct().ToList();
			this.Field_AreaType.Items.AddRange(this.Session.Project.Relocatees.Where(t => !string.IsNullOrEmpty(t.areaType)).Select(t => t.areaType).Distinct().ToArray());
		}

		/// <summary>
		/// 启用编辑
		/// </summary>
		public void BeginEdit()
		{
			this.ButtonSave.Text = "保存";
			this.cancel.Visible = true;
			TextBox textBox;
			foreach (Control control in this.FieldControls)
			{
				textBox = control as TextBox;
				if (textBox == null)
					control.Enabled = true;
				else
					textBox.ReadOnly = false;
			}
			this.cancel.Visible = true;
			this.village_label.Visible = true;
			this.head_label.Visible = true;
			this.input_EnableDate.Enabled = true;
			this.checkBox1.Enabled = true;
			this.checkBox2.Enabled = true;
			this.checkBox3.Enabled = true;
		}

		/// <summary>
		/// 取消编辑
		/// </summary>
		public void EndEdit()
		{
			this.ButtonSave.Text = "修改";
			this.cancel.Visible = false;
			this.village_label.Visible = false;
			this.head_label.Visible = false;
			//this.Field_Area.Enabled = false;
			this.input_EnableDate.Enabled = false;
			TextBox textBox;
			foreach (Control control in this.FieldControls)
			{
				textBox = control as TextBox;
				if (textBox == null)
					control.Enabled = false;
				else
					textBox.ReadOnly = true;
			}
			this.checkBox1.Enabled = false;
			this.checkBox2.Enabled = false;
			this.checkBox3.Enabled = false;
		}

		/// <summary>
		/// 初始化意向安置户型的提示颜色
		/// </summary>
		private void InitHouseCountColour(Relocatee relocate)
		{
			if (this.IsDisposed)
				return;
			ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object obj) {
				try
				{
					ObjectQuery<Relocatees_House> relocatees_house = relocate.Relocatees_House.CreateSourceQuery();
					int type0 = relocatees_house.Where(t => t.House.areatype == 0).Count();
					int type1 = relocatees_house.Where(t => t.House.areatype == 1).Count();
					int type2 = relocatees_house.Where(t => t.House.areatype == 2).Count();
					int type3 = relocatees_house.Where(t => t.House.areatype == 3).Count();
					int type4 = relocatees_house.Where(t => t.House.areatype == 4).Count();
					int type5 = relocatees_house.Where(t => t.House.areatype == 5).Count();
					int type6 = relocatees_house.Where(t => t.House.areatype == 6).Count();
					MethodInvoker methodInvoker_SetColour = new MethodInvoker(delegate() {
						try
						{
							this.Field_HouseType1.BackColor = relocate.housetype1 > type0 ? Color.Red : Color.White;
							this.Field_HouseType2.BackColor = relocate.housetype2 > type1 ? Color.Red : Color.White;
							this.Field_HouseType3.BackColor = relocate.housetype3 > type2 ? Color.Red : Color.White;
							this.Field_HouseType4.BackColor = relocate.housetype4 > type3 ? Color.Red : Color.White;
							this.Field_HouseType5.BackColor = relocate.housetype5 > type4 ? Color.Red : Color.White;
							this.Field_HouseType6.BackColor = relocate.housetype6 > type5 ? Color.Red : Color.White;
							this.Field_HouseType7.BackColor = relocate.housetype7 > type6 ? Color.Red : Color.White;
						} catch (Exception ex)
						{							
							Log.Error(ex.GetInnerExceptionMessage());
							System.Diagnostics.Debug.WriteLine(ex);
							MyMessagebox.Show("操作失败！");
						}

					});
					this.ExecMethodInvoker(methodInvoker_SetColour);
				} catch (Exception ex)
				{
					Log.Error(ex.GetInnerExceptionMessage());
					System.Diagnostics.Debug.WriteLine(ex);
					MyMessagebox.Show("操作时发生错误！");
				}
			}));
		}

		#endregion

		/// <summary>
		/// 保存/修改按钮
		/// </summary>
		private void Save_Click(object sender, EventArgs e)
		{
			try
			{
				if (this.ButtonSave.Text == "修改")
				{
					this.BeginEdit();
					return;
				} else
				{
					if (!this.ValidatorAllControls())
					{
						return;
					}
					this.UseWaitCursor = true;
					this.ButtonSave.Enabled = false;

					//是否是添加新数据
					bool isAdd = this.Relocatee == null;
					if (isAdd)
					{
						this.Relocatee = new Relocatee();
						this.Relocatee.relocatees_id = Relocation.Service.DataModel.GenerateID(this.Relocatee);
						this.Relocatee.created = System.DateTime.Now;
						this.Relocatee.Project = this.Session.Project;
					}
					this.GetValue(this.Relocatee);
					Session.DataModel.Save(this.Relocatee);
					this.FieldIsChanged = false;
					this.Session.GetMainTreeView().RefreshNode(this.Relocatee, isAdd ? EntityState.Added : EntityState.Modified);
					if (isAdd && MyMessagebox.Confirm("数据保存成功，是否添加户主安置情况？").Equals(DialogResult.Yes))
					{
						using (PlacementWindow pWindow = new PlacementWindow(this.Session, this.Relocatee, this.Relocatee.head, "户主"))
						{
							pWindow.Text = "户主安置情况登记";
							pWindow.ShowDialog();
						}
					}
					this.FieldIsChanged = false;

					if (this.tabPages.Visible)
					{
						this.SetValue(this.Relocatee);
						this.EndEdit();
					} else
					{
						this.DialogResult = DialogResult.OK;
						this.Close();
					}

				}
			} catch (Exception ex)
			{
				Log.Error(ex.Message);
				MyMessagebox.Error(ex.Message);
			}
			this.UseWaitCursor = false;
			this.ButtonSave.Enabled = true;


		}

		/// <summary>
		///	取得用户输入的Relocatee
		/// </summary>
		/// <param name="relocatee"></param>
		protected void GetValue(Relocatee relocatee)
		{
			try
			{
				base.GetValueFromInput(relocatee);
				this.Relocatee.updated = System.DateTime.Now;
				this.Relocatee.enabledate = input_EnableDate.Value;
				relocatee.buy1 = this.checkBox1.Checked;
				relocatee.buy2 = this.checkBox2.Checked;
				relocatee.buy3 = this.checkBox3.Checked;
			} catch (Exception ex)
			{				
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				throw;
			}

		}

		/// <summary>
		/// 页面加载Relocatee对象
		/// </summary>
		public void SetValue(Relocatee relocatees)
		{
			try
			{
				List<string> namslist = new List<string>(new string[] { "housetype1", "housetype2", "housetype3", "housetype4", "housetype5", "housetype6", "housetype7" });

				if (relocatees != null)
				{
					person = relocatees.head;

					base.SetValueToInput(relocatees);
					this.input_EnableDate.Value = this.Relocatee.enabledate;
					this.checkBox1.Checked = relocatees.buy1 == null ? false : (bool)relocatees.buy1;
					this.checkBox2.Checked = relocatees.buy2 == null ? false : (bool)relocatees.buy2;
					this.checkBox3.Checked = relocatees.buy3 == null ? false : (bool)relocatees.buy3;
				}
				foreach (Control contorl in this.FieldControls)
				{
					ControlTag tag = contorl.Tag as ControlTag;
					if (tag == null)
						return;
					if (namslist.Contains(tag.FieldName))
					{
						if (string.IsNullOrEmpty(contorl.Text.Trim()))
							contorl.Text = "0";
					}
				}

				InitHouseCountColour(relocatees);
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
			}
			this.FieldIsChanged = false;

		}

		#region 验证

		/// <summary>
		/// 有安置情况下，户主姓名不能修改
		/// </summary>
		private void Head_Validating(object sender, CancelEventArgs e)
		{
			if (this.Relocatee != null)
			{
				if (!this.Relocatee.Placements.IsLoaded)
					this.Relocatee.Placements.Load();

				string headName = this.Relocatee.Placements.Where(t => t.relation.Equals("户主")).Select(t => t.name).FirstOrDefault();
				if (!string.IsNullOrEmpty(headName))
					this.Field_Head.Text = person;
				//foreach (Placement placmentWindow in this.Relocatee.Placements)
				//{
				//        if (placmentWindow.relation == "户主")
				//        {
				//                //MyMessagebox.Show("当前拆迁户下已有安置情况，户主信息不能修改！");
				//                this.Field_Head.Text = person;
				//                break;
				//        }
				//}
			}
		}

		#endregion


		/// <summary>
		/// RelocateesWindow页面刷新
		/// </summary>
		public override void Refresh()
		{
			base.Refresh();
			try
			{
				if (this.Relocatee == null)
				{
					return;
				}
				this.Session.DataModel.Refresh(RefreshMode.StoreWins, this.Relocatee);
				this.SetValue(this.Relocatee);
				if (this.tabPages.Visible && this.tabPagePlacementList.Controls.Count > 0)
				{
					BaseFormList<System.Data.Objects.DataClasses.EntityObject> list = this.tabPagePlacementList.Controls[0] as BaseFormList<System.Data.Objects.DataClasses.EntityObject>;
					if (list != null)
						list.Reload();
				}
			} catch (Exception ex)
			{
				
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				throw;
			}
		}



		/// <summary>
		/// TabControl切换显示安置情况和安置房分配及交款情况
		/// </summary>
		private void TabPlacement_SelectedIndexChanged(object sender, EventArgs e)
		{
			try
			{
				if (this.tabPages.SelectedIndex.Equals(0))
				{
					//如果是安置人员
					if (this.TabListPlacement == null)
					{
						InitPlacementList(this.Relocatee);	//如果安置人员列表未实例化，则初始化安置人员列表
					} else
					{
						this.TabListPlacement.Relocatee = this.Relocatee;	//如果安置人员列表已经实例化，则刷新列表
						this.TabListPlacement.Reload();
					}
				} else
				{
					//如果是安置房列表
					if (this.TabListRelocateesHouse == null)
					{
						InitRelocatees_HouseList(this.Relocatee);
					} else
					{
						this.TabListRelocateesHouse.Relocatee = this.Relocatee;
						this.TabListRelocateesHouse.Reload();
					}
				}

			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				this.MessageBoxError(ex);
			}
		}

		/// <summary>
		/// 更改村庄之后加载相应的单位列表
		/// </summary>		
		private void Village_TextChanged(object sender, EventArgs e)
		{
			try
			{
				this.Field_Village.Text = this.Field_Village.Text.Trim();
				string villageStr = this.Field_Village.Text;
				string org = this.Field_Organization.Text;
				if (!string.IsNullOrEmpty(villageStr))
				{
					this.Field_Organization.DataSource = this.Session.Project.Relocatees.CreateSourceQuery().Where(it => it.village.Equals(this.Field_Village.Text)).Select(t => t.organization).Distinct().ToList();
				}

				this.Field_Organization.Text = string.IsNullOrEmpty(org) ? "" : org;
				this.FieldIsChanged = true;
			} catch (Exception ex)
			{
				Log.Error(ex);
			}
		}

		/// <summary>
		/// 取消修改
		/// </summary>
		private void Cancel_Click(object sender, EventArgs e)
		{
			try
			{
				if (this.tabPages.Visible)
				{
					this.GetErrorProvider().Clear();
					this.SetValue(this.Relocatee);
					this.EndEdit();

				} else
				{
					this.Close();
				}
			} catch (Exception ex)
			{
				Log.Error(ex);
				this.MessageBoxError(ex);
			}

		}

		/// <summary>
		/// 加载拆迁户信息，并默认选中安置人员或安置房
		/// </summary>
		/// <param name="relocatees">拆迁户</param>
		/// <param name="entityObject">安置人员或安置房</param>
		internal void LoadEntity(Relocatee relocatees, EntityObject entityObject)
		{
			try
			{
				if (relocatees == null)
				{
					Log.Error("relocatees参数为空！");
					return;
				}
				if (!this.Relocatee.Equals(relocatees) || entityObject is Relocatee)
				{
					this.Relocatee = relocatees;
					this.InitRelocatee(relocatees);	//加载拆迁户信息				
				}
				InitPageList(relocatees, entityObject);
				this.tabPages.Visible = true;
			} catch (Exception ex)
			{
				Log.Error(ex);
				throw;
			}
		}

		internal void LoadEntity(EntityObject entityObject)
		{
			LoadEntity(this.Relocatee, entityObject);
		}

		/// <summary>
		/// 初始化拆迁户信息
		/// </summary>
		/// <param name="relocatees"></param>
		private void InitRelocatee(Relocatee relocatees)
		{
			this.SetValue(relocatees);
			this.EndEdit();
		}

		private void InitPageList(Relocatee relocatees, EntityObject entityObject)
		{
			try
			{
				if (relocatees == null)
					return;
				Relocatees_House rHouse = entityObject as Relocatees_House;
				if (rHouse != null)
				{

					this.InitRelocatees_HouseList(relocatees);		//初始化安置房列表	
					this.TabListRelocateesHouse.SelectEntity(rHouse);
					this.tabPages.SelectedTab = this.tabPageRelocateesHouseList;
				} else
				{
					this.InitPlacementList(relocatees);	//初始化安置人员列表
					this.TabListPlacement.SelectEntity(entityObject as Placement);
					this.tabPages.SelectedTab = this.tabPagePlacementList;
				}
				if (this.tabPages.Visible == false)
					this.tabPages.Visible = true;
			} catch (Exception ex)
			{
				Log.Error(ex);
				throw;
			}
		}

		private void InitPlacementList(Relocatee relocatees)
		{
			try
			{
				if (this.TabListPlacement == null)
				{
					TabListPlacement = new PlacementList(this.Session, relocatees);
					InitTabForm(TabListPlacement);
					TabListPlacement.Show();
					this.ExecMethodInvoker(new MethodInvoker(delegate() {
						this.tabPagePlacementList.Controls.Add(TabListPlacement);
					}));
				} else
				{
					TabListPlacement.Relocatee = relocatees;
					TabListPlacement.Reload();
				}
			} catch (Exception ex)
			{
				Log.Error(ex);
				throw;
			}
		}

		private void InitRelocatees_HouseList(Relocatee relocatees)
		{
			try
			{
				if (this.TabListRelocateesHouse == null)
				{
					TabListRelocateesHouse = new Relocatees_HouseList(this.Session, relocatees);
					InitTabForm(TabListRelocateesHouse);
					TabListRelocateesHouse.Show();
					this.ExecMethodInvoker(new MethodInvoker(delegate() {
						this.tabPageRelocateesHouseList.Controls.Add(TabListRelocateesHouse);
					}));
				} else
				{
					TabListRelocateesHouse.Relocatee = relocatees;
					TabListRelocateesHouse.Reload();
				}
			} catch (Exception ex)
			{
				Log.Error(ex);
				throw;
			}
		}

		/// <summary>
		/// 设置Tab标签内窗体的属性
		/// </summary>
		/// <param name="TabListPlacement"></param>
		/// <returns></returns>
		private void InitTabForm(Form form)
		{
			form.Dock = DockStyle.Fill;
			form.FormBorderStyle = FormBorderStyle.None;
			form.TopLevel = false;
		}

		private Button GetSaveButtion()
		{
			return this.ButtonSave;
		}


		/// <summary>
		/// 是否处于编辑状态且未保存
		/// </summary>
		public bool IsNoSaved
		{
			get
			{
				return this.FieldIsChanged;
			}
		}
	}
}
